package org.yunai.swjg.server.util;

import java.nio.ByteBuffer;

public class TGWUtil {
    public static void tgwFilter(ByteBuffer msgBuf) {
        if (msgBuf.limit() - msgBuf.position() < 20) {
            return;
        }
        int pre3 = -1;
        int pre2 = -1;
        int pre1 = -1;
        int nowByte = -1;
        int nowPos = msgBuf.position();
        int idxEnd = msgBuf.limit();
        for (int i = nowPos; i < idxEnd; i++) {
            pre3 = pre2;
            pre2 = pre1;
            pre1 = nowByte;
            nowByte = msgBuf.get();
            if (i <= 15) {
                int tValue = getTGWHeadByte(i);
                if (tValue != nowByte) {
                    msgBuf.position(nowPos);
                    return;
                }
            }
            boolean isEnd = isTGWEnd(pre3, pre2, pre1, nowByte);
            if (isEnd) {
                return;
            }
        }
    }

    private static int getTGWHeadByte(int idx) {
        switch (idx) {
            case 0:
                return 116;
            case 1:
                return 103;
            case 2:
                return 119;
            case 3:
                return 95;
            case 4:
                return 108;
            case 5:
                return 55;
            case 6:
                return 95;
            case 7:
                return 102;
            case 8:
                return 111;
            case 9:
                return 114;
            case 10:
                return 119;
            case 11:
                return 97;
            case 12:
                return 114;
            case 13:
                return 100;
            case 14:
                return 13;
            case 15:
                return 10;
        }
        return -1;
    }

    private static boolean isTGWEnd(int pre3, int pre2, int pre1, int nowByte) {
        if (pre3 != 13) {
            return false;
        }
        if (pre2 != 10) {
            return false;
        }
        if (pre1 != 13) {
            return false;
        }
        if (nowByte != 10) {
            return false;
        }
        return true;
    }
}